import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/widget/group_text_filed.dart';
import 'package:image_pickers/image_pickers.dart';

class CommentInputView extends StatefulWidget {
  static const String routeName = 'comment_input';
  final String? hint;
  final TextEditingController textEditController;
  final String? selectedImgPath;
  final Function(String? imgPath)? imgCallback;

  CommentInputView({
    super.key,
    this.hint,
    required this.textEditController,
    this.selectedImgPath,
    this.imgCallback,
  });

  @override
  State<CommentInputView> createState() => _CommentInputViewState();
}

class _CommentInputViewState extends State<CommentInputView> with WidgetsBindingObserver {
  final focus = FocusNode();

  TextEditingController get textEditController => widget.textEditController;
  bool hasShowKeyboard = false;
  bool isImageSelectIng = false;
  String? selectedImgPath;

  @override
  void initState() {
    super.initState();
    selectedImgPath = widget.selectedImgPath;
    textEditController.addListener(() {
      if (mounted) setState(() {});
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      focus.requestFocus();
    });
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // print(MediaQuery.of(context).viewInsets.bottom);
      if (MediaQuery.of(context).viewInsets.bottom == 0) {
        if ((Get.isBottomSheetOpen ?? false) && hasShowKeyboard && !isImageSelectIng) {
          // if (hasShowKeyboard && mounted) {
          hasShowKeyboard = false;
          // Get.back();
          // }
        }
      } else {
        hasShowKeyboard = true;
      }
    });
  }

  void choseImg() async {
    isImageSelectIng = true;
    final listMedia = await ImagePickers.pickerPaths(
      uiConfig: UIConfig(uiThemeColor: Colors.white),
      galleryMode: GalleryMode.image,
      selectCount: 1,
      showCamera: false,
    );
    if (listMedia.isNotEmpty) {
      final ret = listMedia.map((e) => e.path ?? '').toList();
      selectedImgPath = ret.first;
      widget.imgCallback?.call(selectedImgPath!);
    }
    setState(() {});
    Future.delayed(Duration(milliseconds: 500), () {
      isImageSelectIng = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () {
          Get.back();
        },
        child: Container(
            alignment: Alignment.bottomCenter,
            child: GestureDetector(
              onTap: () {},
              child: Container(
                color: Colors.black,
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (selectedImgPath?.isNotEmpty == true)
                      Container(
                        margin: EdgeInsets.only(bottom: 12),
                        width: 60,
                        height: 60,
                        child: Stack(
                          fit: StackFit.expand,
                          children: [
                            Image.file(
                              File(selectedImgPath!),
                              width: 60,
                              height: 60,
                              fit: BoxFit.cover,
                            ),
                            Positioned(
                              top: 0,
                              right: 6,
                              child: GestureDetector(
                                onTap: () {
                                  selectedImgPath = null;
                                  widget.imgCallback?.call(null);
                                  setState(() {});
                                },
                                child: Image.asset(
                                  "close_grey.png".commonImgPath,
                                  width: 12,
                                  height: 12,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    Container(
                      padding: EdgeInsets.symmetric(vertical: 2),
                      height: 72,
                      decoration: BoxDecoration(
                        color: Color(0xff262626),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Column(
                        children: [
                          Expanded(
                            child: GroupTextFiled(
                              focusNode: focus,
                              controller: textEditController,
                              maxLength: 100,
                              alignment: Alignment.topLeft,
                              padding: EdgeInsets.fromLTRB(8, 4, 8, 2),
                              textStyle: TextStyle(color: Colors.white, fontSize: 14),
                              onSubmitted: (value) {
                                Get.back(result: true);
                              },
                              placeholder: widget.hint ?? '在此写下您想说的...',
                              placeholderTextStyle: TextStyle(color: Color(0xff999999), fontSize: 14),
                              decoration:BoxDecoration(),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(right: 6, bottom: 4),
                            alignment: Alignment.centerRight,
                            child: Text(
                              "${textEditController.text.length}/100",
                              style: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 12,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    6.sizeBoxH,
                    Row(
                      children: [
                        Container(
                          margin: EdgeInsets.only(right: 12, top: 4, bottom: 4),
                          child: GestureDetector(
                            onTap: choseImg,
                            child: Image.asset(
                              'icon_pic.webp'.commentPath,
                              width: 24,
                              height: 24,
                            ),
                          ),
                        ),
                        Spacer(),
                        GestureDetector(
                          onTap: () {
                            if (textEditController.text.isEmpty) {
                              showToast('请输入想要说的话哦～～');
                              return;
                            }
                            Get.back(result: true);
                          },
                          child: Image.asset(
                            'ic_send.webp'.commentPath,
                            width: 24,
                            height: 24,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            )),
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
